import requests
import json
from config.logger import setup_logging
from plugins_func.register import register_function, ToolType, ActionResponse, Action

TAG = __name__
logger = setup_logging()

GET_TAOBAO_SUGGEST_FUNCTION_DESC = {
    "type": "function",
    "function": {
        "name": "get_taobao_suggest",
        "description": (
            "获取淘宝商品搜索建议。"
            "根据用户输入的关键词，获取淘宝的商品搜索建议列表。"
            "可用于查询商品相关信息、热门商品名称等。"
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "keyword": {
                    "type": "string",
                    "description": "搜索关键词，例如'手机'、'笔记本'等",
                },
                "lang": {
                    "type": "string",
                    "description": "返回用户使用的语言code，例如zh_CN/zh_HK/en_US/ja_JP等，默认zh_CN",
                },
            },
            "required": ["keyword", "lang"],
        },
    },
}


def fetch_taobao_suggest(keyword):
    """从淘宝接口获取商品搜索建议"""
    try:
        url = f"http://suggest.taobao.com/sug?code=utf-8&q={keyword}&callback=cb"
        response = requests.get(url)
        response.raise_for_status()
        
        # 处理JSONP格式的响应
        content = response.text
        # 去除JSONP回调函数，提取JSON部分
        json_str = content.strip()[3:-1]  # 移除 'cb(' 和 最后的 ')'
        
        # 解析JSON
        result = json.loads(json_str)
        return result
    except Exception as e:
        logger.bind(tag=TAG).error(f"获取淘宝商品建议失败: {e}")
        return {"result": []}


@register_function(
    "get_taobao_suggest",
    GET_TAOBAO_SUGGEST_FUNCTION_DESC,
    ToolType.SYSTEM_CTL,
)
def get_taobao_suggest(conn, keyword: str, lang: str = "zh_CN"):
    """获取淘宝商品搜索建议"""
    try:
        logger.bind(tag=TAG).info(f"获取淘宝商品建议: 关键词={keyword}")
        
        # 获取商品建议
        suggest_data = fetch_taobao_suggest(keyword)
        
        if not suggest_data or "result" not in suggest_data or not suggest_data["result"]:
            return ActionResponse(
                Action.REQLLM, 
                f"根据下列数据，用{lang}回应用户的淘宝商品查询请求：\n\n"
                f"关键词: {keyword}\n"
                f"查询结果: 未找到相关商品建议\n\n"
                f"(请以自然、流畅的方式告知用户未找到相关商品建议)",
                None
            )
        
        # 构建商品建议列表
        suggestions = []
        for item in suggest_data["result"]:
            if len(item) >= 2:
                product_name = item[0]
                product_count = item[1]
                suggestions.append(f"{product_name} (约{product_count}个商品)")
        
        # 构建回复
        suggest_report = (
            f"根据下列数据，用{lang}回应用户的淘宝商品查询请求：\n\n"
            f"搜索关键词: {keyword}\n"
            f"商品建议列表:\n" + "\n".join([f"- {item}" for item in suggestions[:10]]) + "\n\n"
            f"(请以自然、流畅的方式向用户展示这些商品建议，可以适当总结内容，"
            f"直接告诉用户这些是与'{keyword}'相关的淘宝商品建议)"
        )
        
        return ActionResponse(Action.REQLLM, suggest_report, None)
        
    except Exception as e:
        logger.bind(tag=TAG).error(f"获取淘宝商品建议出错: {e}")
        return ActionResponse(
            Action.REQLLM, "抱歉，获取淘宝商品建议时发生错误，请稍后再试。", None
        ) 